package com.ziyan;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.ziyan.pojo.ItemDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


import java.io.IOException;
import java.util.List;


@SpringBootTest(classes = SearchApplication.class)
public class ES {
    @Autowired
    private ItemClient itemClient;

    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.233.129:9200")
        ));
    }

    @Test
    void esTest() throws Exception {
        int i = 1;
        while (true) {
            //调用feign 去itemservice中查询数据
            PageDTO<Item> itemPageDTO = itemClient.list(i, 500);

            List<Item> list = itemPageDTO.getList();

            if (list.size() <= 0){
                break;
            }

                BulkRequest request = new BulkRequest();

            for (Item item : list) {
                ItemDoc doc = new ItemDoc(item);
                request.add(new IndexRequest("tb_item")
                        .id(doc.getId().toString())
                        .source(JSON.toJSONString(doc), XContentType.JSON));
            }
            //利用restHight
            client.bulk(request, RequestOptions.DEFAULT);

            System.out.println(i);
            i++;
        }
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

}
